<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form ref="deptFormRef" :model="form" :rules="rules" label-width="160px">
      <el-form-item :label="$t('sysDept.code')" prop="deptCode">
        <el-input
          v-model="form.deptCode"
          :placeholder="$t('sysDept.codeRequired')"
          maxlength="30"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('sysDept.name')" prop="deptName">
        <el-input
          v-model="form.deptName"
          :placeholder="$t('sysDept.nameRequired')"
          maxlength="30"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('sysDept.type')" prop="deptType">
        <jmash-dict-select
          v-model="form.deptType"
          :placeholder="$t('sysDept.typeRequired')"
          :type-code="Constant.DICT_DEPT_TYPE"
          class="w-full"
        />
      </el-form-item>
      <el-form-item :label="$t('sysDept.parent')" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="deptsArray"
          :render-after-expand="false"
          filterable
          clearable
          check-strictly
          :placeholder="$t('sysDept.parentRequired')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="$t('sysDept.description')" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :autosize="{ minRows: 2 }"
          :placeholder="$t('sysDept.descriptionRequired')"
          clearable
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-row>
        <el-col span="20">
          <el-form-item :label="$t('sysDept.status')" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :value="true">{{ $t("common.enable") }}</el-radio>
              <el-radio :value="false">{{ $t("common.disable") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col span="4">
          <el-form-item :label="$t('sysDept.accessPermiss')" prop="isOpen">
            <el-switch v-model="form.isOpen" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, type PropType } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { type FormInstance, type FormRules, ElMessage } from "element-plus";
import { Constant } from "@/constant";

import type {
  DeptFormReq,
  DeptKey,
  DeptUpdateReq,
} from "@/api/system/dept/types";
import { deptApi } from "@/api/system/dept/index";
const deptFormRef = ref<FormInstance>();
const deptsArray = ref([] as any);
let form: DeptFormReq = reactive({
  requestId: Math.random() * 10 + "",
  updateMask: "deptType,deptCode,deptName,parentId,description,status,isOpen",
  status: true,
});
const rules = reactive<FormRules<DeptFormReq>>({
  deptCode: [
    { required: true, message: t("sysDept.codeRequired"), trigger: "blur" },
  ],
  deptName: [
    { required: true, message: t("sysDept.nameRequired"), trigger: "blur" },
  ],
  deptType: [
    { required: true, message: t("sysDept.typeRequired"), trigger: "change" }
  ]
});
const emits = defineEmits(["refresh"]);
const props = defineProps({
  entityKey: {
    type: Object as PropType<DeptKey>,
    default: () => {},
  },
});

const model = defineModel<boolean>();

function queryDeptData() {
  deptApi.treelistDept(props.entityKey?.deptId).then(({ data }) => {
    deptsArray.value = data.results;
  });
}

const keys = Object.keys(props.entityKey);

const update = ref(keys.length >= 1);

if (update.value) {
  deptApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
    if (form.parentId === "00000000-0000-0000-0000-000000000000") {
      form.parentId = "";
    }
  });
}

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}

// 表单提交
async function submitForm() {
  await deptFormRef.value?.validate((valid) => {
    if (valid) {
      if (update.value) {
        deptApi.update(form as DeptUpdateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      } else {
        deptApi.create(form).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      }
    }
  });
}

queryDeptData();
</script>
<style lang="scss" scoped>
.w-full {
  width: 100% !important;
}
</style>
